﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RGoodSW.Logger.Interfaces;
using CodeCamp.Infrastructure;
using CodeCamp.Models.Shared;

namespace CodeCamp.Controllers
{
    //
    //   http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404-in-asp-net-mvc
    //
    public class ErrorsController : ControllerBase
    {
        public ErrorsController(ILoggerExtended logger)
            : base(logger)
        {
        }

        public ActionResult Index(string eventName)
        {
            string errorMsg = null;
            if (TempData.ContainsKey(TempDataKeys.ErrorMessage))
                errorMsg = TempData[TempDataKeys.ErrorMessage] as string;
            if (!string.IsNullOrWhiteSpace(errorMsg))
                ViewBag.ErrorMsg = errorMsg;

            return View("Error2");
        }

        public ActionResult NotFound()
        {
            ActionResult result = null;
            SetLoggerThreadContextData();

            var model = new NotFoundViewModel();
            // If the url is relative ('NotFound' route) then replace with Requested path 
            model.RequestUrl = this.Request.Url.PathAndQuery;
                //Request.Url.OriginalString.Contains(url) & Request.Url.OriginalString != url ?
                //Request.Url.OriginalString : url;
            // Dont get the user stuck in a 'retry loop' by 
            // allowing the Referrer to be the same as the Request 
            model.ReferrerUrl = (this.Request.UrlReferrer == null) ? null : this.Request.UrlReferrer.PathAndQuery;
                //Request.UrlReferrer != null &&
                //Request.UrlReferrer.OriginalString != model.RequestedUrl ?
                //Request.UrlReferrer.OriginalString : null; 

            //var model = Request.Url.PathAndQuery;

            Logger.WarnFormat("URL was not found. (IsAjaxRequest={1}) {0}URL=\"{2}\" {0}Referrer=\"{3}\" {0}",
                Environment.NewLine,
                Request.IsAjaxRequest(),
                model.RequestUrl,
                model.ReferrerUrl);

            //TO DO -- check for crawler?
            if ((Request.Browser != null) && !string.IsNullOrWhiteSpace(Request.Browser.Browser)
                && (Request.Browser.Browser == "IE"))
            {
                //To make this page show up on IE 9...
                Response.StatusCode = (int)HttpStatusCode.OK;
            }

            if (!Request.IsAjaxRequest())
                result = View("_NotFound", model);
            else
                result = PartialView("_NotFoundPartial", model);

            return result;
        }

    }
}
